package com.group.dao;

import java.util.*;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Transaction;
import org.hibernate.annotations.OrderBy;

import com.group.domain.Media;
import com.group.domain.User;
import com.group.utils.HibernateUtil;
import java.sql.Date; 
/**
 * 书影音数据表操作
 * 
 * @author 86191
 *
 */
public class MediaDao {
	
	/**
	 * 根据id查询
	 * 
	 * @param id
	 * @return
	 */
	public Media findOneById(int id) {
		Session session = HibernateUtil.openSession();
		Media media = null;
		media = (Media) session.get(Media.class, id);
		return media;
	}

	/**
	 * 匹配查询,模糊查询，处理搜索框
	 * 
	 * @param title
	 * @return
	 */
	public List<Media> findBySimilarTitle(String title) {
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Media.class);
		criteria.add(Restrictions.eq("isDelete", false));
		criteria.add(Restrictions.like("title", "%" + title + "%"));
		List<Media> mediaList = criteria.list();
		session.close();
		return mediaList;
	}

	/**
	 * 根据年份、标签和类型筛选media
	 * 
	 * @param year 要匹配的年份
	 * @param tag  要匹配的标签
	 * @param type 要匹配的类型
	 * @return 包含所有匹配的Media对象的List集合
	 * @throws HibernateException 如果查询过程中发生异常，则抛出HibernateException
	 */

	public List<Media> findFilterMedia(String year, String tag, String type) throws HibernateException {
	    Session session = null;
	    try {
	        session = HibernateUtil.openSession();
	        
	        Criteria criteria = session.createCriteria(Media.class);
	        criteria.add(Restrictions.eq("isDelete", false));
	        // 设置年份筛选
	        if (!year.isEmpty()) {
	            Date startDate = Date.valueOf(year + "-01-01");
	            Date endDate = Date.valueOf(year + "-12-31");
	            criteria.add(Restrictions.between("releaseDate", startDate, endDate));
	        }
	        
	        // 设置标签筛选
	        if (!tag.isEmpty()) {
	            criteria.add(Restrictions.eq("tag", tag));
	        }
	        
	        // 设置类型筛选
	        if (!type.isEmpty()) {
	            criteria.add(Restrictions.eq("type", type));
	        }

	        // 设置按年份排序
	        criteria.addOrder(Order.asc("releaseDate")).addOrder(Order.asc("type")).addOrder(Order.asc("tag"));
	        List<Media> mediaList = criteria.list();
	        return mediaList;
	    } catch (HibernateException e) {
	        throw e;
	    } finally {
	        if (session != null) {
	            session.close();
	        }
	    }
	}
	
	/**
	 * 获取筛选后的列表长度
	 * @param year
	 * @param tag
	 * @param type
	 * @return
	 * @throws HibernateException
	 */
	public long countFilterMedia(String year, String tag, String type) throws HibernateException {
	    Session session = null;
	    try {
	        session = HibernateUtil.openSession();

	        Criteria criteria = session.createCriteria(Media.class);
	        criteria.add(Restrictions.eq("isDelete", false));
	        
	        // 设置年份筛选
	        if (!year.isEmpty()) {
	            Date startDate = Date.valueOf(year + "-01-01");
	            Date endDate = Date.valueOf(year + "-12-31");
	            criteria.add(Restrictions.between("releaseDate", startDate, endDate));
	        }
	        
	        // 设置标签筛选
	        if (!tag.isEmpty()) {
	            criteria.add(Restrictions.eq("tag", tag));
	        }
	        
	        // 设置类型筛选
	        if (!type.isEmpty()) {
	            criteria.add(Restrictions.eq("type", type));
	        }

	        // 设置投影以获取count值
	        criteria.setProjection(Projections.rowCount());
	        
	        // 获取count值
	        long count = (Long) criteria.uniqueResult();
	        
	        return count;
	    } catch (HibernateException e) {
	        throw e;
	    } finally {
	        if (session != null) {
	            session.close();
	        }
	    }
	}

	
	/**
	 * 筛选分页
	 * @param year
	 * @param tag
	 * @param type
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * @throws HibernateException
	 */
	public List<Media> findFilterMediaByPage(String year, String tag, String type, int pageNo, int pageSize) throws HibernateException {
	    Session session = null;
	    try {
	        session = HibernateUtil.openSession();

	        Criteria criteria = session.createCriteria(Media.class);
	        criteria.add(Restrictions.eq("isDelete", false));
	        
	        // 设置年份筛选
	        if (!year.isEmpty()) {
	            Date startDate = Date.valueOf(year + "-01-01");
	            Date endDate = Date.valueOf(year + "-12-31");
	            criteria.add(Restrictions.between("releaseDate", startDate, endDate));
	        }
	        
	        // 设置标签筛选
	        if (!tag.isEmpty()) {
	            criteria.add(Restrictions.eq("tag", tag));
	        }
	        
	        // 设置类型筛选
	        if (!type.isEmpty()) {
	            criteria.add(Restrictions.eq("type", type));
	        }

	        // 设置按年份排序
	        criteria.addOrder(Order.asc("releaseDate")).addOrder(Order.asc("type")).addOrder(Order.asc("tag"));
	        
	        // 获取符合条件的所有结果
	        List<Media> mediaList = criteria.list();
	        
	        // 进行分页处理
	        int startIndex = (pageNo - 1) * pageSize;
	        int endIndex = Math.min(startIndex + pageSize, mediaList.size());
	        List<Media> paginatedList = mediaList.subList(startIndex, endIndex);

	        return paginatedList;
	    } catch (HibernateException e) {
	        throw e;
	    } finally {
	        if (session != null) {
	            session.close();
	        }
	    }
	}


	/**
	 * 返回指定type的media列表
	 * 
	 * @param type
	 * @return
	 */
	public List<Media> findMeidaListByType(String type) {
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Media.class);
		criteria.add(Restrictions.eq("isDelete", false));
		criteria.add(Restrictions.eq("type", type));
		List<Media> mediaList = criteria.list();
		session.close();
		return mediaList;
	}

	/**
	 * 返回所有的media列表
	 * 
	 * @param type
	 * @return
	 */
	public List<Media> findAllMedia() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			Criteria criteria = session.createCriteria(Media.class);
			criteria.add(Restrictions.eq("isDelete", false));
			List<Media> mediaList = criteria.list();
			return mediaList;
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 通过title获取Media
	 * 
	 * @param title	书/影/音的标题（名称）
	 * @return			指定标题的书/影/音
	 */
	public Media findOneByTitle(String title) {
		Session session = HibernateUtil.openSession();
		Media media = null;
		media = (Media) session.get(Media.class, title);
		return media;
	}
	
	/**
	 * 保存media
	 * @param media	要保存的media
	 * @return				是否保存成功
	 */
	public boolean saveMedia(Media media) {
		Session session = HibernateUtil.openSession();
		Transaction transaction = null;
		int result = 0;
		try {
			transaction = session.beginTransaction();
			result = (Integer) session.save(media);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		} finally {
			session.close();
		}
		return result > 0;
	}
	
	/**
	 * 分页查询用户列表
	 * 
	 * @param pageNum	页码
	 * @return						指定页码下的用户列表
	 */
	@OrderBy(clause = "id ASC")
	public List<Media> findMediaListByPage(int pageNo, int pageSize) {
		Session session = HibernateUtil.openSession();
        List<Media> mediaList = null;
        try {
            Criteria criteria = session.createCriteria(Media.class);
            criteria.add(Restrictions.eq("isDelete", false));
            // 设置排序条件
            criteria.addOrder(Order.asc("id"));
            // 设置分页信息
            criteria.setFirstResult((pageNo - 1) * pageSize);
            criteria.setMaxResults(pageSize);
            // 获取用户列表
            mediaList = criteria.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return mediaList;
	}
	
	/**
	 * 分页分类型获取media列表
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@OrderBy(clause = "id ASC")
	public List<Media> findTypeListByPage(int pageNo, int pageSize,String type) {
	    Session session = HibernateUtil.openSession();
	    List<Media> musicMediaList = null;
	    try {
	        Criteria criteria = session.createCriteria(Media.class);
	        criteria.add(Restrictions.eq("isDelete", false));
	        // 设置类型
	        criteria.add(Restrictions.eq("type", type));
	        // 设置排序
	        criteria.addOrder(Order.asc("id"));
	        // 设置分页
	        criteria.setFirstResult((pageNo - 1) * pageSize);
	        criteria.setMaxResults(pageSize);
	        // 获取media列表
	        musicMediaList = criteria.list();
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        session.close();
	    }
	    return musicMediaList;
	}

	/**
	 * 返回所有Media对象的总数
	 * @return Media对象的总数
	 * @throws HibernateException 如果查询过程中发生异常，则抛出HibernateException
	 */
	public long count() {
		Session session = HibernateUtil.openSession();
		long count = 0;
		try {
			count = (long) session.createQuery("SELECT COUNT(*) FROM Media WHERE isDelete = false").uniqueResult();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("Error");
		} finally {
			session.close();
		}
		return count;
	}
	
	/**
	 * 获取指定类型的media个数
	 * @param type		指定类型
	 * @return				指定类型的media个数
	 */
	public long countMeida(String type) {
	    Session session = HibernateUtil.openSession();
	    long count = 0;
	    try {
	        count = (long) session.createQuery("SELECT COUNT(*) FROM Media WHERE type = :mediaType AND isDelete = false")
	                .setParameter("mediaType", type)
	                .uniqueResult();
	    } catch (Exception e) {
	        e.printStackTrace();
	        System.out.println("Error");
	    } finally {
	        session.close();
	    }
	    return count;
	}

	/**
	 * 编辑media信息
	 * 
	 * @param media		新的信息
	 * @return					是否编辑成功
	 */
	public boolean update(Media media) {
		Session session = HibernateUtil.openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.update(media);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		} finally {
			session.close();
		}
		return true;
	}
	
	/**
	 * 通过title模糊查找
	 * 
	 * @param title	指定title
	 * @return			模糊查找的结果
	 */
	public List<Media> findMediaListByTitle(String title){
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Media.class);
		criteria.add(Restrictions.eq("isDelete", false));
		// 设置排序条件
        criteria.addOrder(Order.asc("id"));
        // 获取media列表
        criteria.add(Restrictions.like("title","%"+title+"%"));
        List<Media> mediaList = criteria.list();
        session.close();
        return mediaList;
	}
	
	/**
	 * 分页模糊查找title
	 * 
	 * @param title			指定title
	 * @param pageNo	页码
	 * @param pageSize	每页的media个数
	 * @return
	 */
	public List<Media> findMediaListByTitle (String title,int pageNo,int pageSize ){
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Media.class);
		criteria.add(Restrictions.eq("isDelete", false));
		// 设置排序条件
        criteria.addOrder(Order.asc("id"));
        // 获取media列表
        criteria.add(Restrictions.like("title","%"+title+"%"));
        // 设置分页信息
        criteria.setFirstResult((pageNo - 1) * pageSize);
        criteria.setMaxResults(pageSize);
        //获取media列表
        List<Media> mediaList = criteria.list();
        session.close();
        return mediaList;
	}
	
	/**
	 * 删除指定id的media
	 * 
	 * @param id		指定id
	 * @return			是否删除成功
	 */
	public boolean delete(int id) {
		Session session = HibernateUtil.openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Media media = session.get(Media.class, id);
			media.setIsDelete(true);
			session.update(media);
			transaction.commit();
			return true;	
		}catch(Exception e){
			e.printStackTrace();
			transaction.rollback();
			return false;
		}finally {
			session.close();
		}
		
	}
	
}
